@extends('layouts.back_stage')
@section('content')
    <style>
        .address {
            border-color: #cfdadd;border-radius: 2px;width: 150px;
            height: 30px;padding: 6px 10px;font-size: 12px;line-height: 1.42857143;margin-right:10px;
            color: #555;background-color: #fff;background-image: none;border: 1px solid #cfdadd;box-shadow: none;
            -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
            -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
        }
        table,th,td{text-align: center}
        b{color:red;}
        .count_sp{padding-bottom:20px;display:inline-block;}
        .count_status{padding-bottom:20px;display:inline-block;font-weight: bolder;}
        .loading-results{
            display: none!important;
        }
        .select2-search__field{
            display: none!important;
        }
        .js-example-basic-single{
            width: 150px;
            outline: none;
        }
        .company-info{
            margin-right:15px;
        }
        .get-top{
            margin-left:10px;
        }
        .startDistribution{
            display: none;
            margin-bottom: 20px;
            margin-left:10px;
        }
        .checkDistribution{
            padding:5px;
        }
        .removeDistribution{
            display: none;
            margin-left:10px;
        }
        .showDisInfo{
            cursor: pointer;
        }
        .table-info button{
            display: inline-block;
            margin-right:5px;
        }
        .model-box{
            width: 500px;
            position: fixed;
            height:100%;
            right:-500px;
            top:0;
            background-color:white;
            z-index: 9999;
            box-shadow: 0 0 5px #ccc;
            transition: all 0.5s;
            padding:20px;
        }
        .close-model{
            width:30px;
            height:30px;
            font-size:20px;
            float: right;  
            border: none;
            outline: none;
        }
        .choose-row{
            background: white;
        }
        .mask-box{
            width:100%;
            height:100%;
            position: fixed;
            z-index: 9998;
            background-color:rgba(0, 0, 0, 0.5);
            left:0;
            top:0;
            display: none;
        }
        .buffer_pool_box{
            width:100%;
            display: block;
            overflow: hidden;
        }
        .buffer_pool{
            width:150px;
            margin:0.5%;
            padding:0.5%;
            height:30px;
            background-color:#e3f3f8;
            transition: all 0.5s;
            float: left;
        }
        .buffer_pool:hover{
            box-shadow: 0 0 5px gray;
        }
        .buffer_pool:hover .remove_pool{
            display: inline;
        }
        .remove_pool{
            margin-left:5px;
            display: none;
            color:red;
            text-decoration: none;
            cursor: pointer;
            float: right;
        }
        .remove_pool:hover{
            color:red!important;
        }
    </style>
    <link rel="stylesheet" href="{{env('CDN_DOMAIN_NAME')}}/css/commoncss/select2.min.css">
    <link rel="stylesheet" href="{{env('CDN_DOMAIN_NAME')}}/css/commoncss/number-pb.css?v0.0.1">
    <div class="container">
        <div style="padding:20px 0;"><h3>整手配货</h3><a href="/picking/distribution-record?type=1" class="btn btn-info" style="float:right;">配货记录</a></div>
        <div style="width: 100%;margin-bottom: 20px;overflow: hidden;">
            <label class="company-info">大品文化创意有限公司</label>
            <label>
                <b>*</b>款号:</label>
            <input class="address girard" type="text" placeholder="输入款号" value="">
            <label>
                <b>*</b>颜色：</label>
            <select class="js-example-basic-single">
                <option value="">请选择</option>
            </select>
            <label>订单状态：</label>
            <select name="status" class="address order_status">
                <option value="">请选择</option>
                <option value="0">未配货</option>
                <option value="1">部分配货</option>
                <option value="2">配货完成</option>
            </select>
            <button type="submit" class="btn btn-info serach_table" style="margin-bottom:2px;">搜索</button>
        </div>
        <div class="buffer_pool_box">
            <ul>

            </ul>
        </div>
        <span class="count_sp"></span>
        <span class="count_status"></span>
        <table class="table table-hover table-info" id="default-table">
            <thead>
                <tr>
                    <th class="col-sm-1"><button class="btn btn-info allChoose" type="1">全选</button></th>
                    <th class="col-sm-1">客户姓名</th>
                    <th class="col-sm-1">订货类型</th>
                    <th class="col-sm-1">订单状态</th>
                    <th class="col-sm-1">款号</th>
                    <th class="col-sm-1">订单数量/手</th>
                    <th class="col-sm-2">已配货</th>
                    <th class="col-sm-1">未配货</th>
                    <th class="col-sm-2">操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <div style="float: right">
            <button class="btn btn-info startDistribution" abc="2">深度配货</button>
            <button class="btn btn-info startDistribution" abc="1">广度配货</button>
            <button class="btn btn-info removeDistribution" abc="1">停止配货</button>
        </div>
        <div class="mask-box"  onclick="closeModel()"></div>
        <div class="model-box">
            <button class="close-model" onclick="closeModel()"><i class="fa fa-close"></i></button>
            <h3>配货信息</h3>
            <table class="table distributionInfo">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>包码编号</th>
                    </tr>
                </thead>
                <tbody>
                    
                </tbody>
            </table>
        </div>
    </div>
    <script src="{{env('CDN_DOMAIN_NAME')}}/js/commonjs/select2.min.js"></script>
    <script src="{{env('CDN_DOMAIN_NAME')}}/js/commonjs/table-dragger.min.js"></script>
    <script src="{{env('CDN_DOMAIN_NAME')}}/js/commonjs/number-pb.js"></script>
    <script src="{{env('CDN_DOMAIN_NAME')}}/js/commonjs/jquery.velocity.min.js"></script>
    <script>
        var dragger;
        $(document).ready(function(){
            $.ajax({
                url:'/picking/get-online-picking',
                type:'get',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                },
                type:'get',
                dataType:'json',
                data:{
                },
                success:function(res){
                    if(res.result.success == true){
                        var option = '';
                        $.each(res.content.info,function(idx,obj){
                            option += '<tr class="handle" id="number_'+obj.id+'">'+
                                '<td><input type="checkbox" name="checkUp" class="checkDistribution" id="'+obj.id+'" /></td>'+
                                '<td>'+obj.username+'</td>'+
                                '<td>'+returnSourceType(obj.source_type)+'</td>'+
                                returnOrderStatus(obj.order_status)+
                                '<td>'+obj.girard+'</td>'+
                                '<td>'+obj.size_2+'</td>'+
                                '<td class="showDisInfo" abc="'+obj.id+'"><div class="number-pb" hander="'+obj.over_num+'" abc="'+parseInt(obj.over_num/obj.size_2*100)+'"><div class="number-pb-shown"></div><div class="number-pb-num">0%</div></div><span>'+obj.over_num+'</span></td>'+
                                '<td>'+(obj.size_2-obj.over_num)+'</td>'+
                                '<td><button class="btn btn-info get-top">置顶</button><button class="btn btn-info get-bottom">置底</button><i class="fa fa-bars"></i></td>'+
                            '</tr>'
                        });
                        if(res.content.type == 1){
                            $('.count_status').text('当前配货状态：广度配货');
                        }else if(res.content.type == 2){
                            $('.count_status').text('当前配货状态：深度配货');
                        }
                        $('.table-info tbody').html(option);
                        for(var i = 0;i<$('.number-pb').length;i++){
                            var num = $('.number-pb').eq(i).attr('abc');
                            $('.number-pb').eq(i).NumberProgressBar({
                                duration: 1200,
                                percentage: num
                            });
                        };
                        $('.removeDistribution').show();
                        $('.table-info tbody tr').css('cursor','not-allowed');
                        $('.table-info tbody button').attr('disabled','disabled');
                        $('.checkDistribution').attr('checked',true);
                        $('.checkDistribution').attr('disabled','disabled');
                        $('.girard').val(res.content.info[0].girard);
                        $('.girard').attr('disabled','disabled');
                        $('.js-example-basic-single').html('<option value="">'+res.content.info[0].color+'</option>');
                        $('.js-example-basic-single').attr('disabled','disabled');
                        $('.serach_table').attr('disabled','disabled');
                        $('.order_status').attr('disabled','disabled');
                    }else{
                        if(!sessionStorage.getItem('girard')){
                        }else{
                            $('.girard').val(sessionStorage.getItem('girard'));
                        }
                        if(!sessionStorage.getItem('color')){
                        }else{
                            $('.js-example-basic-single').html('<option value="'+sessionStorage.getItem('color')+'">'+sessionStorage.getItem('color')+'</option>');
                        }
                    }
                },
            });
            $('.js-example-basic-single').select2({
                minimumResultsForSearch:-1,
                ajax: {
                    url: "/picking/girardColor",
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                    return {
                        girard:$('.girard').val()
                    };
                    },
                    processResults: function (data) {
                        $('.js-example-basic-single').select2('data',null);
                        if(data.result.success == true){
                            if(data.content.results[0] == undefined){
                                $(".faceImg").attr("src","/img/weep.png");
                                $(".oHandle").text('没有该款号');
                                $(".oSuccess").show(0).delay(1000).hide(0);
                                return {
                                    results: data.content.results
                                };
                            }else{
                                return {
                                    results: data.content.results
                                };
                            }
                        }else{
                            $(".faceImg").attr("src","/img/weep.png");
                            $(".oHandle").text(data.result.errorMsg);
                            $(".oSuccess").show(0).delay(1000).hide(0);
                            return false;
                        }
                    },
                    cache: true
                },
                escapeMarkup: function (markup) { return markup; }, 
            });
            $.ajax({
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
                url: '/picking/get-virtual-pool',
                type: 'get',
                data: {
                },
                dataType: 'json',
                success: function(res) {
                    if(res.result.success == true){
                        $.each(res.content,function(idx,obj){
                            $('.buffer_pool_box ul').append('<li class="buffer_pool">'+
                            '<span>'+obj+'</span><a href="javascript:;" class="remove_pool">X</a>'+
                            '</li>')
                        });
                    }else{
                        $(".faceImg").attr("src","/img/weep.png");
                        $(".oHandle").text(data.result.errorMsg);
                        $(".oSuccess").show(0).delay(1000).hide(0);
                        return false;
                    }
                }
            });
        });
        $('.serach_table').click(function(){
            var girard = $('.address').val();
            var color = $(".js-example-basic-single").select2("val");
            var order_status = $('.order_status').val();
            if(girard==''){
                $(".faceImg").attr("src","/img/weep.png");
                $(".oHandle").text("请输入款号");
                $(".oSuccess").show(0).delay(1000).hide(0);
                return false;
            }
            if(color==''){
                $(".faceImg").attr("src","/img/weep.png");
                $(".oHandle").text("请选择颜色");
                $(".oSuccess").show(0).delay(1000).hide(0);
                return false;
            }
            $.ajax({
                url:'/picking/funtures-orders',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                },
                type:'get',
                dataType:'json',
                data:{
                    order_type:1,
                    color:color,
                    girard:girard,
                    order_status:order_status
                },
                success:function(res){
                    if(res.result.success == true){
                        var option = '';
                        var checkCount=0;
                        sessionStorage.setItem('girard',girard);
                        sessionStorage.setItem('color',color);
                        $.each(res.content,function(idx,obj){
                            option += '<tr class="handle" id="number_'+obj.id+'">'+
                                '<td><input type="checkbox" name="checkUp" class="checkDistribution" '+returnDisabled(obj.order_status)+' id="'+obj.id+'" /></td>'+
                                '<td>'+obj.username+'</td>'+
                                '<td>'+returnSourceType(obj.source_type)+'</td>'+
                                returnOrderStatus(obj.order_status)+
                                '<td>'+obj.girard+'</td>'+
                                '<td>'+obj.size_2+'</td>'+
                                '<td class="showDisInfo" abc="'+obj.id+'"><div class="number-pb" hander="'+obj.over_num+'" abc="'+parseInt(obj.over_num/obj.size_2*100)+'"><div class="number-pb-shown"></div><div class="number-pb-num">0%</div></div><span>'+obj.over_num+'</span></td>'+
                                '<td>'+(obj.size_2-obj.over_num)+'</td>'+
                                '<td><button class="btn btn-info get-top">置顶</button><button class="btn btn-info get-bottom">置底</button><i class="fa fa-bars"></i></td>'+
                            '</tr>';
                            checkCount++;
                        });
                        // console.log(checkCount);
                        $('.count_sp').text('共'+checkCount+'条信息');
                        $('.table-info tbody').html(option);
                        for(var i = 0;i<$('.number-pb').length;i++){
                            var num = $('.number-pb').eq(i).attr('abc');
                            $('.number-pb').eq(i).NumberProgressBar({
                                duration: 1200,
                                percentage: num
                            });
                        }
                        $('.startDistribution').show();
                        $('.removeDistribution').hide();
                        dragger = tableDragger(document.querySelector("#default-table"),{ mode:"row",onlyBody:true,dragHandler:'.handle' })
                            .on('drop', (from, to, el, mode) => {
                                console.log(`drop ${el.nodeName} from ${from} ${mode} to ${to} ${mode}`);

                            })
                    }
                }
            })
        });
        $(document).on('click','.get-top',function(){
            var parent = $(this).parent().parent();
            if(parent.index() != 0){
                var tr = parent.clone(true);
                parent.remove();
                $('.table-info ').prepend(tr);
                dragger.destroy();
                dragger = tableDragger(document.querySelector("#default-table"),{ mode:"row",onlyBody:true,dragHandler:'.handle' })
                    .on('drop', (from, to, el, mode) => {
                        console.log(`drop ${el.nodeName} from ${from} ${mode} to ${to} ${mode}`);
                    })
            }else{
                $(".faceImg").attr("src","/img/weep.png");
                $(".oHandle").text('已经是第一位了');
                $(".oSuccess").show(0).delay(1000).hide(0);
            }
        });
        $(document).on('click','.get-bottom',function(){
            var parent = $(this).parent().parent();
            if(parent.next().length != 0){
                var tr = parent.clone(true);
                parent.remove();
                $('.table-info ').append(tr);
                dragger.destroy();
                dragger = tableDragger(document.querySelector("#default-table"),{ mode:"row",onlyBody:true,dragHandler:'.handle' })
                    .on('drop', (from, to, el, mode) => {
                        console.log(`drop ${el.nodeName} from ${from} ${mode} to ${to} ${mode}`);
                    })
            }else{
                $(".faceImg").attr("src","/img/weep.png");
                $(".oHandle").text('已经是最后一位了');
                $(".oSuccess").show(0).delay(1000).hide(0);
            }
        });
        function returnOrderStatus(type){
            if(type == 0){
                return "<td>未配货</td>"
            }else if(type == 1){
                return "<td style='color:green'>部分配货</td>"
            }else if(type == 2){
                return "<td style='color:skyblue'>全部配货</td>"
            }
        }
        function returnSourceType(type){
            if(type == 1){
                return "订货"
            }else if(type == 2){
                return "加单"
            }
        }
        function returnDisabled(status){
            if(status == 2){
                return "disabled"
            }else{
                return ""
            }
        }
        $('.allChoose').click(function(){
            var type = $(this).attr('type');
            if(type == 1){
                $('.checkDistribution').each(function(){
                    if(typeof($(this).attr('disabled')) == "undefined"){
                        $(this).prop("checked",true);
                    }
                });
                $(this).text('取消全选');
                $(this).attr('type','2')
            }else if(type == 2){
                $('.checkDistribution').removeAttr("checked",false);
                $(this).text('全选');
                $(this).attr('type','1')
            }
        })
        $('.startDistribution').click(function(){
            var picking_type = $(this).attr('abc');
            var order_ids = "";
            for(var i = 0;i<$('.checkDistribution:checked').length;i++){
                order_ids += $('.checkDistribution:checked').eq(i).attr('id')+",";
            }
            if(order_ids == ""){
                $(".faceImg").attr("src","/img/weep.png");
                $(".oHandle").text('请勾选你要配货的订单');
                $(".oSuccess").show(0).delay(1000).hide(0);
                return false;
            }
            var girard = $('.address').val();
            var color = $(".js-example-basic-single").select2("val");
            $.ajax({
                url:'/picking/start-picking',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                },
                type:'post',
                dataType:'json',
                data:{
                    picking_type:picking_type,
                    order_ids:order_ids,
                    assembly_num:1,
                    type:1,
                    girard:girard,
                    color:color
                },
                success:function(res){
                    if(res.result.success == true){
                        $('.checkDistribution').attr('disabled','disabled');
                        $('.js-example-basic-single').attr('disabled','disabled');
                        $('.serach_table').attr('disabled','disabled');
                        $('.order_status').attr('disabled','disabled');
                        $('.girard').attr('disabled','disabled');
                        $('.checkDistribution').not('input:checked').parent().parent().hide();
                        $('.checkDistribution:checked').attr('disabled','disabled');
                        $('.removeDistribution').show();
                        $('.startDistribution').hide();
                        dragger.destroy();
                        $('.table-info tbody tr').css('cursor','not-allowed');
                        $('.table-info tbody button').attr('disabled','disabled');
                        if(picking_type == 1){
                            $('.count_status').text('当前配货状态：广度配货');
                        }else if(picking_type == 2){
                            $('.count_status').text('当前配货状态：深度配货');
                        }
                        $('.count_status').show();
                    }else{
                        $(".faceImg").attr("src","/img/weep.png");
                        $(".oHandle").text(res.result.errorMsg);
                        $(".oSuccess").show(0).delay(1000).hide(0);
                    }
                }
            })
        });
        $('.removeDistribution').click(function(){
            $(this).attr("disabled","disabled");
            $.ajax({
                url:'/picking/stop-picking',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                },
                type:'post',
                dataType:'json',
                data:{
                    assembly_num:1,
                },
                success:function(res){
                    if(res.result.success == true){
                        $(".faceImg").attr("src","/img/laugh.png");
                        $(".oHandle").text('停止成功');
                        $(".oSuccess").show(0).delay(1000).hide(0);
                        setTimeout(function(){
                            window.location.reload();
                        },1000)
                    }else{
                        $(".faceImg").attr("src","/img/weep.png");
                        $(".oHandle").text(res.result.errorMsg);
                        $(".oSuccess").show(0).delay(1000).hide(0);
                        $(this).removeAttr("disabled");
                    }
                }
            })
        });
        $(document).on('click','.showDisInfo',function(){
            var id = $(this).attr('abc');
            $('.distributionInfo tbody').html();
            $(this).parent().addClass('choose-row');
            $(this).parent().siblings().removeClass('choose-row');
            $.ajax({
                url:'/picking/get-picking-info',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                },
                type:'get',
                dataType:'json',
                data:{
                    order_id:id,
                },
                success:function(res){
                    if(res.result.success == true){
                        $('.model-box').css('right','0px');
                        $('.distributionInfo tbody').html("");
                        $.each(res.content,function(idx,obj){
                            $('.distributionInfo tbody').prepend('<tr>'+
                                '<td>'+(Number(idx)+1)+'</td>'+
                                '<td>'+obj.qrcode+'</td>'+
                            '</tr>');
                        });
                        $('.mask-box').show();
                        $('.model-box').attr('abc',id);
                    }
                }
            })
        });
        function closeModel(){
            $('.model-box').css('right','-500px');
            $('.table-info tr').removeClass('choose-row');
            $('.mask-box').hide();
        }
        var domain_name = '{{ env('DOMAIN_NAME') }}';
        ws = new WebSocket("wss://"+domain_name+":8282");
        ws.onopen = function() {
//        ws.send('1');
        };
        ws.onmessage = function(e) {
            var data = eval("("+e.data+")");
            var type = data.type || '';
            var client_id = data.client_id;
            console.log(e);
            switch(type){
                case 'init':
                    $.ajax({
                        url:'/picking/picking-socket-init',
                        type:'POST',
                        data:{ass_num:1,client_id:client_id},
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
                        },
                        dataType:'json',
                        success:function(data){
                            if(data.success == true)
                            {
                            }else{
                            }
                        }
                    });
                break;
                case  'picking':
                    var over_num = Number($('#number_'+data.order_id+' .number-pb').siblings('span').text())+1;
                    var sum_num = Number($('#number_'+data.order_id+' .number-pb').parent().prev().text());
                    $('#number_'+data.order_id+' .number-pb').NumberProgressBar().reach(parseInt(over_num/sum_num*100));
                    $('#number_'+data.order_id+' .number-pb').attr('hander',over_num);
                    $('#number_'+data.order_id+' .number-pb').siblings('span').text(over_num);
                    $('#number_'+data.order_id+' .number-pb').parent().next().text(sum_num-over_num);
                    var length = $('.distributionInfo tbody').children().length;
                    if(data.order_id == $('.model-box').attr('abc')){
                        $('.distributionInfo tbody').prepend('<tr>'+
                                '<td>'+(Number(length)+1)+'</td>'+
                                '<td>'+data.code+'</td>'+
                            '</tr>')
                    }
                break;
                case  'picking_over':
                    $(".oText").text("本次配货全部完成");
                    $(".oMask").show();
                    $(".oAnim").show();
                    $(".oBtn1").hide();
                    $(".oContent img").hide();
                break;
                case 'virtual_pool_add':
                    var code = data.code;
                    $('.buffer_pool_box ul').append('<li class="buffer_pool">'+
                        '<span>'+code+'</span><a href="javascript:;" class="remove_pool">X</a>'+
                    '</li>');
                break;
                case 'virtual_init':
                    $('.buffer_pool_box ul').html("");
                break;
            }
        };
        $(document).on('click','.oBtn0',function(){
            window.location.reload();
        });
        $(document).on('click','.checkDistribution',function(){
            if($(this).siblings('.id_status').text() == "全部配货"){
                $(".faceImg").attr("src","/img/weep.png");
                $(".oHandle").text('该订单已经完成配货，不可勾选');
                $(".oSuccess").show(0).delay(1000).hide(0);
                return false;
            }
        });
        $(document).on('mouseover','.select2',function(){
            if($('.girard').val() == ""){
                $('.js-example-basic-single').attr('disabled','disabled');
                $(".faceImg").attr("src","/img/weep.png");
                $(".oHandle").text('请填写款号');
                $(".oSuccess").show(0).delay(1000).hide(0);
            }else{
                $('.js-example-basic-single').removeAttr('disabled');
            }
        });
        $(document).on('click','.remove_pool',function(){
            var that = $(this);
            var order_num = $(this).siblings('span').text();
            var checkRemove = confirm("请确认是否删除？")
            if(!checkRemove){
                return false;
            }
            $.ajax({
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
                url: '/picking/delete-virtual-pool-code',
                type: 'post',
                data: {
                    code:order_num
                },
                dataType: 'json',
                success: function(res) {
                    if(res.result.success == true){
                        $(".faceImg").attr("src","/img/laugh.png");
                        $(".oHandle").text('删除完成');
                        $(".oSuccess").show(0).delay(1000).hide(0);
                        that.parent().remove();
                    }else{
                        $(".faceImg").attr("src","/img/weep.png");
                        $(".oHandle").text(res.result.errorMsg);
                        $(".oSuccess").show(0).delay(1000).hide(0);
                    }
                }
            });
        });
    </script>
@endsection